package com.example.bluetooth_test;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ConnectedThread extends Thread {
    private final BluetoothSocket mSocket;
    private final Handler mHandler;
    private OutputStream mOutStream;
    private InputStream mInStream;

    public ConnectedThread(BluetoothSocket socket, Handler handler) {
        this.mSocket = socket;
        this.mHandler = handler;

        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mInStream = tmpIn;
        mOutStream = tmpOut;
    }

    public void run() {
        //定义字节数组变量，用于流的缓冲存储
        byte[] buffer = new byte[1024];
        int bytes = 0;
        int ch ;
        /*
        持续监听输入流，直到出现异常
         */
        while (true) {

            try {
//                bytes = mInStream.read(buffer);
                //当接收到的字符不是“\n”时，将字符存在字节数组中
                while ((ch = mInStream.read()) != '\n'){
                    //如果收到的字符为空字符，read（）会返回-1，则不存储在字节数组中
                    if (ch !=-1){
                        buffer[bytes] = (byte) ch;
                        bytes++;
                    }
                }
                buffer[bytes] = (byte) '\n';
                bytes++;
//                if (bytes > 0) {
//                String msg = new String(buffer, 1, bytes, "utf-8");
                  mHandler.obtainMessage(Constant.STATE_MESSAGE_RECEIVED, bytes, -1, buffer).sendToTarget();
                  buffer = new byte[1024];
//                mHandler.sendMessage(message);
//                Control.mHandler.obtainMessage(Constant.STATE_MESSAGE_RECEIVED, bytes, -1, buffer).sendToTarget();
//                }
            } catch (IOException e) {
                e.printStackTrace();
                mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR));
            }
        }
    }
    /*
    在main函数中调用此函数，将数据发送到远端设备中。
     */
    public void write(byte[] bytes){
        try {
            mOutStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void cancel() {
        try {
            mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
